package com.xiaoma.socket

import android.app.AppOpsManager
import android.app.Application
import androidx.core.content.getSystemService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update

object PermissionManager {
    private val context = MutableStateFlow<Application?>(null)

    private val _granted = MutableStateFlow(false)
    val granted: StateFlow<Boolean> = _granted

    fun prepare(app: App) = context.update { app }

    suspend fun refresh() {
        val context = context.filterNotNull().first()
        val aom = context.getSystemService<AppOpsManager>()
        val mode = aom?.unsafeCheckOpNoThrow(
            AppOpsManager.OPSTR_GET_USAGE_STATS,
            context.applicationInfo.uid,
            context.packageName
        )
        _granted.update {
            mode == AppOpsManager.MODE_ALLOWED
        }
    }

}